package cn.spikego.advicelite.client.core.command

import cn.spikego.advicelite.client.AdviceLite
import cn.spikego.advicelite.client.core.command.impl.HelpCommand
import cn.spikego.advicelite.client.core.event.impl.PlayerChatEvent
import cn.spikego.advicelite.client.eventapi.EventManager
import cn.spikego.advicelite.client.eventapi.EventTarget

class CommandManager {

    private val commandList: MutableList<Command> = ArrayList()

    fun initialize() {
        commandList.add(HelpCommand())
        EventManager.register(this)
    }

    @EventTarget
    fun onChat(event: PlayerChatEvent) {
        val message = event.getMessage()
        message?.let {
            if (it.startsWith(",")) {
                val args = message.split(" ").toTypedArray()
                val command = args[0].substring(1)
                val commandObject = commandList.firstOrNull { it.getPrefix().equals(command, ignoreCase = true) }
                if (commandObject != null) {
                    try {
                        commandObject.execute(args)
                    } catch (e: Exception) {
                        try {
                            AdviceLite.getMinecraftUtil()?.sendSystemMessage("&cFailed to execute command!")
                            e.printStackTrace()
                        } catch (e1: Exception) {
                            e1.printStackTrace()
                        }
                    }
                } else {
                    try {
                        AdviceLite.getMinecraftUtil()?.sendSystemMessage("&cCommand not found!")
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                }
                event.setCancelled(true)
            }
        }
    }

    fun getCommandList(): List<Command> = commandList
}